class ProfileController < ApplicationController
  layout "default"  
  
  def index
    show
  end
  
  def show
    get_owner
    @profile = @owner.profile
    if !@profile
      profile = Profile.new
      profile.user_id = params[:id]
      profile.save!
      @profile = profile
    end
    @visitor = User.find_by_id(session[:user_id])
    @wall    = Wall.find_by_profile_id(@profile.id)
  end
  
  def edit
    @owner   = User.find_by_id(session[:user_id])
    @profile = Profile.find_by_user_id(session[:user_id])
    
    if request.post?
      # check for empty field to calculate percentage
      filled_fields = 0
      field_count = 0
      
      params[:profile].each { |field| 
       if !field[1].blank?
         filled_fields = filled_fields+1
       end
       puts field.inspect
       field_count = field_count+1
      }
      percentage = (field_count / filled_fields) * 100

      @owner.completed = percentage
      @owner.save!
      
      if @profile.update_attributes(params[:profile])
        flash[:success] = "Dein Profil wurde erfolgreich gespeichert!"
        redirect_to :action => :show, :id => @profile.user_id
      end
    end
  end
  
  private
  
  def get_owner
    @owner   = User.find_by_id(params[:id])
  end

  def authorize
    redirect_to :controller => :user, :action => :login if !session[:user_id]
  end

end
